import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.model_selection import GridSearchCV

# 读取数据集
df = pd.read_csv("new_file_with_scores_kmeans.csv")

# 定义特征列
features = ['Q3', 'Q4', 'Q5', 'Q6', 'Q11']

# 创建KMeans对象并指定种子值
random_state = 42  # 设置种子值为42
kmeans = KMeans(random_state=random_state)


# 定义轮廓系数评估函数
def silhouette_scorer(estimator, X):
    labels = estimator.fit_predict(X)
    score = silhouette_score(X, labels)
    return score


# 设置聚类数量的搜索范围
param_grid = {'n_clusters': range(3, 11)}

# 设置循环次数
num_trials = 5

# 初始化存储得分的列表
scores = []

for _ in range(num_trials):
    # 使用网格搜索确定最佳的聚类数量
    grid_search = GridSearchCV(kmeans, param_grid=param_grid, scoring=silhouette_scorer)
    grid_search.fit(df[features])

    # 获取最佳分数
    best_score = grid_search.best_score_

    # 将得分添加到列表中
    scores.append(best_score)

# 创建一个DataFrame来存储得分
score_df = pd.DataFrame({'Trial': range(1, num_trials + 1), 'Silhouette Score': scores})

# 绘制得分的折线图
plt.figure(figsize=(10, 6))
plt.plot(score_df['Trial'], score_df['Silhouette Score'], marker='o', color='skyblue', linestyle='-')
plt.xlabel('Trial')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Score for Each Trial')
plt.xticks(np.arange(1, num_trials + 1))
plt.grid(True)
plt.show()

# 显示得分汇总表
print(score_df)

# 保存最佳的KMeans模型
best_kmeans = grid_search.best_estimator_
best_kmeans_seed = random_state

# 使用最佳的 KMeans 模型进行聚类预测
best_kmeans_labels = best_kmeans.fit_predict(df[features])

# 将聚类结果添加到数据集中作为新列
df['KMeans_Label'] = best_kmeans_labels
# 打印每个聚类的聚类中心
print("\nCluster centers:")
for i, center in enumerate(best_kmeans.cluster_centers_):
    print(f"Cluster {i}: {center}")

#
# # 保存修改后的数据集
# df.to_csv("new_file_with_kmeans_labels.csv", index=False)

